<?php
session_start(); // 开启会话
// page 访问次数
// 连接数据库
$servername = "localhost";
$mysqluser = "root";
$dbpass = "mysql123456";
$dbname = "student";
try {
    
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $mysqluser, $dbpass, array(
        PDO::ATTR_PERSISTENT => true
    ));
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (isset($_POST['update_page_visit']) && $_POST['update_page_visit'] == 1) {
            // 处理更新页面访问次数请求
            if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
                throw new Exception('用户未登录');
            }
            $user_id = $_POST['user_id'];
            $current_file = $_POST['current_file'];

            // 检查用户是否已经在 pagevisi 表中
            $stmt = $conn->prepare("SELECT number FROM pagevisi WHERE id = :user_id");
            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($result) {
                // 如果用户已经存在，更新访问次数
                $new_number = $result['number'] + 1;
                $stmt = $conn->prepare("UPDATE pagevisi SET number = :new_number WHERE id = :user_id");
                $stmt->bindParam(':new_number', $new_number, PDO::PARAM_INT);
                $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                $stmt->execute();
            } else {
                // 如果用户不存在，插入新记录
                $new_number = 1;
                $stmt = $conn->prepare("INSERT INTO pagevisi (id, number, page) VALUES (:user_id, :new_number, :current_file)");
                $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                $stmt->bindParam(':new_number', $new_number, PDO::PARAM_INT);
                $stmt->bindParam(':current_file', $current_file, PDO::PARAM_STR);
                $stmt->execute();
                echo '新用户记录插入成功';
            }

            // 查询当前页面的总访问次数
            $stmt = $conn->prepare("SELECT SUM(number) as total_number FROM pagevisi WHERE page = :current_file");
            $stmt->bindParam(':current_file', $current_file, PDO::PARAM_STR);
            $stmt->execute();
            $sum_result = $stmt->fetch(PDO::FETCH_ASSOC);
            $_SESSION['page_visit'] = $sum_result['total_number'];

            echo '页面访问次数更新成功';
        }
    }
} catch (PDOException $e) {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        echo '数据库操作失败: ' . $e->getMessage();
    } elseif ($_SERVER["REQUEST_METHOD"] == "GET") {
        http_response_code(500);
        echo json_encode(array('error' => '数据库查询失败: ' . $e->getMessage()));
    }
}
?>